/**
 * 路由鉴权
*/
//@ts-ignore
import router from "@/router/index.ts";

//引入仓库数据
//@ts-ignore
import { useUserStore } from "./store/userStore";

//引入Element-plus
//@ts-ignore
import { showToast } from "vant";



//全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
    const userStore = useUserStore ();
    //获取token判断用户是否登录
    let token  = userStore.token || localStorage.getItem("token"); 
    //if token
    if(token){
        //曾登录过
        if(to.path == '/login') {
            next({path:"/home"});
        } else {
            //获取用户名或手机号信息
            let userinfo = userStore.userInfo.username || userStore.userInfo.phone;
            if(userinfo){
                //有用户名或手机号信息,直接放行
                next();
            } else {
                let username = null;
                try {
                    username = localStorage.getItem("username") || (JSON.parse(localStorage.getItem("userInfo"))).username;
                    await userStore.getUserInfo(username);
                    next({...to});
                } catch (error) {
                    showToast("身份过期,请重新登录!");
                    next({path:"/login"});
                }
            }
        }
        
    }else{
        //未登录
        if(to.path == '/login' || to.path == '/home' || to.path == '/search' || to.path == '/category' || to.path == '/detail' || to.path == '/register' || to.path == '/forget'){
            //未登录情况下可以访问首页、登录页、分类页、详情页、忘记密码页、注册页
            next();
        }else{
            next({path:'/login',query:{redirect:to.path}});
        }
    }
})


//全局后置守卫
router.afterEach((to: any, from: any) => {

})